import React, { Component } from 'react';
import { Table, Space, Button, Input, Breadcrumb, Row, Col, Divider, Tree, message, Tooltip, Select, Form, TreeSelect, Modal, Popconfirm } from 'antd';
import { AppstoreTwoTone, FormOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import BraftEditor from 'braft-editor';
import { connect } from 'dva'
import styles from "./index.less"
import TextArea from 'antd/lib/input/TextArea';

const { confirm } = Modal;
const { Option } = Select
@connect((global) => ({
    userInfo: global.userInfo,
}))
class ArticleClassifyForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editorState: BraftEditor.createEditorState(null),//富文本
            isModalVisible: false,
            secondModalVisible: false,
            oneDirList: [],//一级目录
            treeNodeId: "",//目录id
            parentId: "",//父类id
            isAdd: true,
            form: {},//帮助文档
            defaultValue: "",
            defaultTitle: "",
            modaltitle: "",
            treeData: [],//分类树
            data: [],//二级目录表数据
            selectedNode: "",
            dirTypeList: [],//目录类型
            treeCode: "",//选择目录的code
            ids: "",//子节点所有id
        }
    }

    componentDidMount() {
        this.getHelp()
        this.setState({
            editorState: BraftEditor.createEditorState(),


            formloading: true
        })
    }
    //获取帮助文档列表
    getHelpList = () => {
        console.log(this.state.selectedNode)
        this.props.dispatch({
            type: "global/getHelpByPage",
            payload: {
                pageSize: 10,
                pageNum: 1,
                catalog: "",
                content: "",
                title: "",
                parentId: "",
                ids: [this.state.treeCode, ...this.state.ids].join(",")
            }
        }).then(res => {
            console.log(res)
            if (res) {
                res.data.rows.map(item => {
                    item.key = item.id
                })
                this.setState({
                    data: res.data.rows
                })
            }
        })
    }
    //获取分类树
    getHelp = () => {
        const { dispatch } = this.props
        dispatch({
            type: "global/getHelp",
            payload: {

            }
        }).then(res => {
            console.log(res)
            let ids = []
            if (res) {
                res.data.forEach((item, index) => {
                    item.key = item.id
                    item.title = item.catalog
                    if (index === 0) {
                        item.children.map(item => {
                            ids.push(item.id)
                            item.children.map(item => {
                                ids.push(item.id)
                            })
                        })
                    }
                    item.children.forEach((item) => {
                        item.title = item.catalog
                        item.key = item.id
                        item.children.forEach(item => {
                            item.title = item.catalog
                            item.key = item.id
                        })
                    })
                })
                this.setState({
                    treeData: res.data,
                    oneDirList: res.data,//父级目录
                    selectedNode: res.data[0].catalog,
                    defaultTitle: res.data[0].catalog,
                    treeCode: res.data[0].id,
                    ids: ids
                }, () => this.getHelpList())
            }
        })
    }
    //添加分类目录
    createDirEvent = () => {
        this.setState({
            secondModalVisible: true,
            isAdd: true,
            defaultTitle: "",
            isSelect: false,
            treeNodeId: null,
            parentId: null
        })
    }
    //目录编辑
    editeDirEvent = () => {
        const { selectedNode, treeCode } = this.state
        console.log(selectedNode, treeCode)
        if (selectedNode && treeCode) {
            this.setState({
                secondModalVisible: true,
                isAdd: false
            })
        } else {
            message.warning("请先选择编辑节点")
        }
    }
    //点击树节点
    treeOnSelect = (selectedKeys, e) => {
        console.log(selectedKeys, e)
        let ids = []
        e.node.children.map(item => {
            ids.push(item.id)
            item.children.map(item => {
                ids.push(item.id)
                item.children.map(item => {
                    ids.push(item.id)
                })
            })
        })
        this.setState({
            selectedNode: e.node.title,
            defaultTitle: e.node.title,
            treeCode: e.node.id,
            ids: ids
        }, () => this.getHelpList())
    }
    //目录的新增编辑保存
    handleOneOk = () => {
        const { treeCode, parentId, defaultTitle, isAdd } = this.state
        console.log(treeCode, parentId, defaultTitle)
        this.props.dispatch({
            type: "global/helpSave",
            payload: {
                id: isAdd ? "" : treeCode,//新增不传
                catalog: defaultTitle,//目录名称
                parentId: isAdd ? parentId : null,//空是根目录 编辑不传
                helpType: 1,
                isDeleted: 2,//1不删  2删除
            }
        }).then(res => {
            console.log(res)
            if (res.code === "1") {
                message.success(res.msg)
                this.getHelp()
                this.setState({
                    isModalVisible: false,
                    secondModalVisible: false
                })
            } else {
                message.error(res.msg)
            }
        })
    }
    //目录删除
    onRightClickEvent = ({ event, node }) => {
        console.log(node)
        Modal.confirm({
            title: '确定删除当前节点?',
            icon: <ExclamationCircleOutlined />,
            content: '删除前请确保当前目录下无子节点或文档',
            onOk: () => {
                console.log('OK');
                this.props.dispatch({
                    type: "global/helpDelete",
                    payload: {
                        id: node.id
                    }
                }).then(res => {
                    if (res.code === "1") {
                        message.success(res.msg)
                        this.getHelp()
                    } else {
                        message.error(res.msg)
                    }
                })
            },
            // onCancel:()=> {
            //     console.log('Cancel');
            // },
        });
    }
    //选择父类目录
    parentSelectChange = (value) => {
        console.log(value)
        this.setState({
            parentId: value
        })
    }

    /////////////
    //文档新增
    createSecondClassfy = () => {
        console.log("添加")
        this.setState({
            form: {
                title: "",
                content: "",
                parentId: this.state.treeCode,
                catalog: "",
                createUser: "",
                modifyUser: "",
                helpType: 0
            },
            isModalVisible: true,
            modaltitle: "帮助文档新增",
        })
    }

    //文档编辑
    editorEvent = (record) => {
        console.log('record', record)
        this.setState({
            isModalVisible: true,
            defaultValue: record.title,
            modaltitle: "文档编辑",
            form: {
                id: record.id,
                title: record.title,
                content: record.content,
                parentId: this.state.treeCode,
                catalog: "",
                createUser: record.createUser,
                modifyUser: record.modifyUser,
                helpType: 0
            }
        })
    }

    //帮助文档编辑增加的提交
    handleOk = () => {
        const { form } = this.state
        console.log('form', form)
        this.props.dispatch({
            type: "global/helpSave",
            payload: form
        }).then(res => {
            console.log(res)
            this.getHelp()
        })
        this.setState({
            isModalVisible: false,
            secondModalVisible: false
        })
    }
    handleChange = (editorState) => {

        const { form } = this.state;
        let url = editorState.toHTML();
        let url1 = url.substr(url.indexOf('>') + 1);
        let content1 = url1.substr(0, url1.indexOf('</'));
        this.setState({
            editorState,
            form: { ...form, content: content1 }
        })
    }
    handleCancel = () => {
        this.setState({
            isModalVisible: false,
            secondModalVisible: false
        })
    }
    //文档删除
    handleDelete = (record) => {
        console.log(record)
        this.props.dispatch({
            type: "global/helpDelete",
            payload: {
                id: record.id
            }
        }).then(res => {
            console.log(res)
            message.success("删除成功！")
            this.getHelp()
        })
    }


    render() {

        let { treeData, selectedNode, isModalVisible, secondModalVisible, defaultTitle, modaltitle, data, form, dirTypeList } = this.state;

        const columns = [
            // {
            //     title: '目录标题',
            //     dataIndex: 'catalog',
            //     key: 'catalog',
            //     // render: (text, record, index) => `${index + 1 + (currentPage - 1) * 10}`,
            //     align: "center",
            //     width: 100
            // },

            {
                title: '帮助文档名称',
                dataIndex: 'title',
                key: 'title',
                align: "center",
                width: 200
            },
            {
                title: '帮文档内容',
                dataIndex: 'content',
                key: 'content',
                align: "center",
                ellipsis: true,
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
                key: 'createTime',
                align: "center",
                width: 100
            },
            {
                title: '更新时间',
                dataIndex: 'modifyTime',
                key: 'modifyTime',
                align: "center",
                width: 100
            },
            {
                title: '操作',
                key: 'action',
                align: "center",
                width: 200,
                render: (text, record, index) => (
                    <Space size="middle">
                        <Button type="primary"
                            icon={<FormOutlined />}
                            size="small" shape="round"
                            style={{ background: "#11bf94" }}
                            onClick={() => this.editorEvent(record)}>编辑</Button>
                        <Popconfirm title="是否确实删除?" onConfirm={() => this.handleDelete(record)}>
                            <Button type="primary"
                                icon={<DeleteOutlined />}
                                danger
                                size="small"
                                shape="round"
                                // onClick={() => this.handleDelete(record)}
                                >删除</Button>
                        </Popconfirm>

                    </Space>
                ),
            },
        ]
        return (
            <div>
                <div className={styles.pagetop}>
                    <span className={styles.pageheader}>
                        <Breadcrumb>
                            <Breadcrumb.Item><AppstoreTwoTone />帮助</Breadcrumb.Item>
                            <Breadcrumb.Item>
                                <a href="/help">帮助列表</a>
                            </Breadcrumb.Item>
                        </Breadcrumb>
                    </span>
                </div>
                <div style={{ background: "white" }}>
                    <Row>
                        <Col span={5} style={{ minHeight: "550px" }}>
                            <div>
                                <div style={{ paddingLeft: "10%", marginTop: "3%" }}>
                                    <span style={{ marginRight: "10%" }}><Button type="primary" onClick={this.editeDirEvent}>编辑目录</Button></span>
                                    <span style={{ marginRight: "10%" }}><Button type="primary" onClick={this.createDirEvent}>添加目录</Button></span>
                                </div>
                                <span style={{ margin: "10px 20px", float: "left" }}>
                                    <Tooltip title="右击删除" color="red" placement="rightTop">
                                        <Tree
                                            defaultExpandAll
                                            onSelect={this.treeOnSelect}
                                            treeData={treeData}
                                            onRightClick={this.onRightClickEvent}
                                        />
                                    </Tooltip>
                                </span>
                            </div>
                        </Col>
                        <Divider type="vertical" style={{ minHeight: "550px" }} />
                        <Col span={18}>
                            <div>
                                <div style={{ marginTop: "10px" }}>
                                    <span className={styles.rightHeadText}>
                                        <Divider type="vertical" />
                                        {selectedNode}
                                        <Divider type="vertical" />
                                    </span>
                                    <span><Button type="primary" onClick={this.createSecondClassfy}>添加帮助文档</Button></span>
                                </div>
                            </div>
                            <Divider />
                            <Table
                                columns={columns}
                                dataSource={data}
                                pagination={false}
                                bordered
                            />
                        </Col>
                    </Row>
                </div>
                {/* 文档添加编辑弹框 */}
                {
                    isModalVisible ?
                        <Modal
                            okText="确定"
                            cancelText="取消"
                            width={800}
                            title={modaltitle}
                            visible={isModalVisible}
                            onOk={this.handleOk}
                            onCancel={this.handleCancel}>
                            <Form initialValues={form} size="middle">
                                <Form.Item label="创建人">
                                    <Input placeholder="请输入创建人" defaultValue={form.createUser} onChange={(e) => this.setState({ form: { ...form, createUser: e.target.value } })} />
                                </Form.Item>
                                <Form.Item label="更新人">
                                    <Input placeholder="请输入更新人" defaultValue={form.modifyUser} onChange={(e) => this.setState({ form: { ...form, modifyUser: e.target.value } })} />
                                </Form.Item>
                                <Form.Item label="文档名称">
                                    <Input placeholder="请输入文档名称" defaultValue={form.title} onChange={(e) => this.setState({ form: { ...form, title: e.target.value } })} />
                                </Form.Item>
                                {/* <Form.Item label="文档内容">
                                    <TextArea rows={10} defaultValue={form.content} onChange={(e) => this.setState({ form: { ...form, content: e.target.value } })} />
                                </Form.Item> */}

                                <Form.Item label="文章内容">
                                    <div style={{ background: "#EFFBFB", margin: "10px" }}>
                                        <BraftEditor
                                            value={form.content}
                                            placeholder="请输入文章内容"
                                            onChange={this.handleChange}
                                        // controls={ controlsdata }
                                        // extendControls={  }
                                        />
                                    </div>
                                </Form.Item>

                            </Form>
                        </Modal> : null
                }
                {/* 分类编辑添加弹框 */}
                {
                    secondModalVisible ?
                        <Modal
                            okText="确定"
                            cancelText="取消"
                            title={this.state.isAdd ? "目录新增" : "目录编辑"}
                            visible={secondModalVisible}
                            onOk={this.handleOneOk}
                            onCancel={this.handleCancel}
                            width={400}>
                            {
                                this.state.isAdd ?
                                    <TreeSelect
                                        placeholder="请选择父节点"
                                        value={this.state.parentId}
                                        treeData={this.state.oneDirList}
                                        onChange={this.parentSelectChange}
                                        style={{ width: "100%" }} />
                                    : null
                            }
                            <Input placeholder="请输入目录名称" style={{ marginTop: "5% ", width: "100%" }} value={defaultTitle} onChange={(e) => this.setState({ defaultTitle: e.target.value })} />
                        </Modal> : null
                }
            </div>
        );
    }
}

export default ArticleClassifyForm;